<template>
	<div>
		<CustomDialog :title="state.dialog.title" v-model:visible="state.dialog.isShowDialog" dialogWidth="900px" @close="closeDialog">
			<!-- <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" @close="closeDialog"> -->
			<splitpanes class="default-theme" @resize="paneSize = $event[0].size">
				<pane :size="15">
					<div class="slider-content">
						<div>
							<el-button @click="allCatalog" class="w100">全部商品</el-button>
						</div>
						<div class="slider-tree">
							<el-tree
								:data="state.catalogData"
								:props="state.catalogProps"
								node-key="id"
								default-expand-all
								@node-click="onClickCatalog"
								:expand-on-click-node="false"
							>
							</el-tree>
						</div>
					</div>
				</pane>
				<pane :size="85">
					<el-card shadow="hover">
						<div class="mb15">
							<el-form ref="tableSearchRef" size="default" :model="goodsSearchState" label-width="100px" class="table-form">
								<el-row>
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
										<el-form-item label="商品名称" prop="goodsName">
											<el-input size="default" placeholder="请输入商品名称" clearable style="width: 100%" v-model="goodsSearchState.goodsName">
											</el-input>
										</el-form-item>
									</el-col>

									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-show="state.isToggle">
										<el-form-item label="创建时间" prop="searchDateTime">
											<el-date-picker
												type="datetimerange"
												v-model="goodsSearchState.searchDateTime"
												start-placeholder="创建开始时间"
												end-placeholder="创建时间"
												style="width: 100%"
											/>
										</el-form-item>
									</el-col>

									<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8" :class="{ mt10: state.isToggle }">
										<el-form-item class="table-form-btn" label-width="10px">
											<!-- <div class="table-form-btn-toggle ml10 cursor-pointer" @click="state.isToggle = !state.isToggle">
                        <span>{{ state.isToggle ? '收筛选' : '展筛选' }}</span>
                        <SvgIcon :name="state.isToggle ? 'ele-ArrowUp' : 'ele-ArrowDown'" />
                      </div> -->
											<el-button size="default" type="primary" class="ml10" @click="handleSearchGoods">
												<el-icon>
													<ele-Search />
												</el-icon>
												查询
											</el-button>
										</el-form-item>
									</el-col>
								</el-row>
							</el-form>
						</div>
						<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%" @selection-change="handleSelectionGoods">
							<!--							<el-table-column type="selection" width="55" />-->
							<el-table-column label="商品名称" prop="title"> </el-table-column>
							<el-table-column label="商品图片" show-overflow-tooltip>
								<template #default="scope">
									<el-image
										:src="scope.row.showPicUrl"
										fit="contain"
										class="image"
										:preview-src-list="[scope.row.showPicUrl]"
										:preview-teleported="true"
									></el-image>
								</template>
							</el-table-column>

							<el-table-column label="零售价格" prop="price"> </el-table-column>

							<el-table-column label="商品原价" prop="originalPrice"> </el-table-column>

							<el-table-column label="操作" show-overflow-tooltip width="220" fixed="right">
								<template #default="scope">
									<el-button size="small" text type="primary" v-if="hasChoiceIds.includes(scope.row.id)" disabled>已选择</el-button>
									<el-button size="small" text type="primary" @click="onChoiceGoods(scope.row)" v-else>选择</el-button>
								</template>
							</el-table-column>
						</el-table>
						<el-pagination
							class="mt15"
							:pager-count="10"
							:page-sizes="[10, 20, 30, 50, 100]"
							v-model:current-page="state.tableData.paging.currentPage"
							background
							v-model:page-size="state.tableData.paging.pageSize"
							layout="total, sizes, prev, pager, next, jumper"
							:total="state.tableData.paging.totalCount"
						>
						</el-pagination>
					</el-card>
				</pane>
			</splitpanes>

			<template #footer>
				<div class="dialog-footer">
					<el-button @click="closeDialog" size="default">取 消</el-button>
					<!--					<el-button type="primary" @click="batchChoiceGoods" size="default">批量选择</el-button>-->
				</div>
			</template>
		</CustomDialog>
		<!-- </el-dialog> -->
		<el-popover ref="catalogPopoverRef" trigger="click" popper-class="custom-popper">
			<el-tabs class="demo-tabs" v-model="defaultTab" @tab-change="tabChange">
				<el-tab-pane :label="item.catalogName" :name="item.id" :key="item.id" v-for="item in state.catalogData">
					<el-cascader-panel :options="item.children" :props="state.catalogProps" @change="choiceCatalog" v-model="goodsSearchState.categoryIds">
					</el-cascader-panel>
				</el-tab-pane>
			</el-tabs>
		</el-popover>
	</div>
</template>
<script setup lang="ts" name="GoodsItemChoice">
import { goodsApi } from '/@/api/goods/index';
import { goodCatalogApi } from '/@/api/goods/catalog/index';
import { ArrowDown } from '@element-plus/icons-vue';
import msg from '/@/utils/messageUtils';
import _ from 'lodash';
const catalogPopoverRef = ref();

const defaultTab = ref();
import { reactive, ref, watch } from 'vue';

import 'splitpanes/dist/splitpanes.css';

import { Splitpanes, Pane } from 'splitpanes';
const paneSize = ref(50);

const emit = defineEmits(['choice']);

const goodsSearchState = reactive({
	goodsName: '',
	categoryId: '',
	status: '',
	categoryIds: [] as any,
	startSearchDateTime: null,
	endSearchDateTime: null,
	searchDateTime: [],
});

const state = reactive({
	isToggle: true,
	choiceIds: [],
	dialog: {
		title: '选择商品',
		isShowDialog: false,
	},
	tableData: {
		data: [],
		total: 0,
		loading: false,
		paging: {
			currentPage: 1,
			pageSize: 10,
			totalCount: null,
			totalPages: null,
		},
	},
	catalogData: [] as any,
	choiceCatalogInfos: [] as ChoiceCatalogInfo[],
	catalogProps: {
		multiple: true,
		label: 'catalogName',
		value: 'id',
		checkStrictly: true,
		emitPath: false,
	},
});

// 商品分类  id 对应 名称
let mapCatalogInfo = new Map();

// 大的分类下面的选中商品分类信息
let mapCatalogIdInfo = new Map();

const tabChange = (value: any) => {
	// tab-change
	console.log('value: ', value);
	defaultTab.value = value;
};

const choiceCatalog = (obj: any) => {
	console.log('obj: ', obj);
	console.log('obj: ', obj);
	mapCatalogIdInfo.set(defaultTab.value, obj);
	console.log('mapCatalogIdInfo: ', mapCatalogIdInfo);
	state.choiceCatalogInfos = [];
	goodsSearchState.categoryIds = [];
	mapCatalogIdInfo.forEach((v, k) => {
		console.log('k: ', k, ' , v: ', v);
		v.forEach((e) => {
			const cci: ChoiceCatalogInfo = {
				catalogId: e,
				catalogType: k,
				catalogName: mapCatalogInfo.get(e),
			};
			state.choiceCatalogInfos.push(cci);
			goodsSearchState.categoryIds.push(e);
		});
	});
};

const deleteChoiceCatalogInfo = (cci: ChoiceCatalogInfo) => {
	const index = _.findIndex(state.choiceCatalogInfos, (e) => e.catalogId == cci.catalogId);
	state.choiceCatalogInfos.splice(index, 1);
	const ids = _.map(state.choiceCatalogInfos, (e) => e.catalogId);
	goodsSearchState.categoryIds = ids;
};

const onLoadCatalogData = async () => {
	try {
		const { data } = await goodCatalogApi().all();
		console.log('all.....: ', data);
		defaultTab.value = data[0].id;
		data.forEach((element: any) => {
			setMapCatalogIdAndName(element.children);
		});
		console.log('defaultTab.value: ', defaultTab.value);
		state.catalogData = data;
	} catch (error) {
		console.log(error);
		msg().error('获取分类父分类失败');
	}
};

const setMapCatalogIdAndName = (obj: any) => {
	obj.forEach((e: any) => {
		mapCatalogInfo.set(e.id, e.catalogName);
		if (!_.isEmpty(e.children)) {
			setMapCatalogIdAndName(e.children);
		}
	});
};

const closeDialog = () => {
	state.dialog.isShowDialog = false;
};

const onClickCatalog = (node: any) => {
	console.log('node: ', node);
	if (goodsSearchState.categoryId != node.id) {
		goodsSearchState.categoryId = node.id;
		onHandleCurrentChange(1);
	}
};

const allCatalog = () => {
	if (goodsSearchState.categoryId != '') {
		goodsSearchState.categoryId = '';
		onHandleCurrentChange(1);
	}
};

const onLoadCatagorygData = async () => {
	// try {
	// 	const { data } = await goodCatalogApi().tree();
	// 	state.catalogData = data;
	// } catch (error) {
	// 	msg().error('获取商品分类失败');
	// }
};

const handlerCategory = () => {
	onLoadCatagorygData();
};
let hasChoiceIds = [] as any[];
const openDialog = (ids: any) => {
	state.dialog.isShowDialog = true;
	handlerCategory();
	onLoadCatalogData();
	getTableData();
	hasChoiceIds = ids;
};
const choiceGoodsItems: ChoiceGoodsItem[] = [];
const handleSelectionGoods = (val: any[]) => {
	console.log('val: ', val);
	choiceGoodsItems.splice(0, choiceGoodsItems.length);
	val.forEach((obj) => {
		const choiceGoodsItem: ChoiceGoodsItem = {
			id: obj.id,
			image: obj.image,
			showPicUrl: obj.showPicUrl,
			title: obj.title,
			keywords: obj.keywords,
			price: obj.price,
			originalPrice: obj.originalPrice,
			stock: obj.stock,
			sales: obj.sales,
			subTitle: obj.subTitle,
		};
		choiceGoodsItems.push(choiceGoodsItem);
	});
};

const onChoiceGoods = (obj: any) => {
	console.log('单个选择: ', obj);
	const choiceGoodsItem: ChoiceGoodsItem = {
		id: obj.id,
		image: obj.image,
		showPicUrl: obj.showPicUrl,
		title: obj.title,
		keywords: obj.keywords,
		price: obj.price,
		originalPrice: obj.originalPrice,
		stock: obj.stock,
		sales: obj.sales,
		subTitle: obj.subTitle,
	};
	emit('choice', [choiceGoodsItem]);
	closeDialog();
};

const batchChoiceGoods = () => {
	emit('choice', choiceGoodsItems);
	closeDialog();
};
const getCatalogIds = () => {
	if (goodsSearchState.categoryId != '') {
		return [goodsSearchState.categoryId];
	}
	return [];
};

const getTableData = async () => {
	try {
		const { data } = await goodsApi().search({
			categoryId: goodsSearchState.categoryId,
			status: goodsSearchState.status,
			catalogIds: getCatalogIds(),
			searchStartTime: goodsSearchState.startSearchDateTime,
			searchEndTime: goodsSearchState.endSearchDateTime,
			goodsName: goodsSearchState.goodsName,
			offset: (state.tableData.paging.currentPage - 1) * state.tableData.paging.pageSize,
			limit: state.tableData.paging.pageSize,
		});
		state.tableData.data = data.datas;
		state.tableData.paging.currentPage = data.paging.currentPage;
		state.tableData.paging.totalCount = data.paging.totalCount;
		console.log('data： ', data);
	} catch (error) {
		msg().error('查询商品列表失败，请稍后重试');
	}
	state.tableData.loading = false;
};
watch(
	() => state.tableData.paging.currentPage,
	(newV, oldv) => {
		console.log(`currentPage, newV: ${newV}, oldV : ${oldv}`);
		onHandleCurrentChange(newV);
	}
);

watch(
	() => state.tableData.paging.pageSize,
	(newV, oldv) => {
		console.log(`pageSize, newV: ${newV}, oldV : ${oldv}`);
		onHandleSizeChange(newV);
	}
);

const onHandleSizeChange = (val: number) => {
	state.tableData.paging.pageSize = val;
	state.tableData.paging.currentPage = 1;
	getTableData();
};

const onHandleCurrentChange = (val: number) => {
	state.tableData.paging.currentPage = val;
	getTableData();
};

const handleSearchGoods = () => {
	const st: any = goodsSearchState.searchDateTime;
	if (st != null && st.length > 0) {
		goodsSearchState.startSearchDateTime = st[0].getTime();
		goodsSearchState.endSearchDateTime = st[1].getTime();
	} else {
		goodsSearchState.startSearchDateTime = null;
		goodsSearchState.endSearchDateTime = null;
	}

	onHandleCurrentChange(1);
};

defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.category-tag-wrap {
	flex: 1;
	min-height: 32px;
	//padding-right: 12px;
	border-radius: 4px;
	border: 1px solid #d9d9d9;
	cursor: pointer;
	position: relative;
	//padding-left: 10px;
	//padding-top: 8px;
	//padding-left: 12px;
	// padding: 8px 12px;
}

.category-tag-wrap-suffix {
	width: 12px;
	height: 100%;
	position: absolute;
	right: 6px;
	top: 0;
	display: flex;
	align-items: center;
	justify-content: center;
}

.el-popper.custom-popper {
	min-width: unset;
	width: fit-content !important;
}

.slider-content {
	width: 100%;
	overflow-x: auto;
	height: 100%;
}
.slider-tree {
	max-width: 100%;
	overflow-y: auto;
	overflow-x: auto;
	max-height: calc(90vh - 111px) !important;
	// padding: 5px;
}

//max-height: calc(90vh - 111px) !important;
</style>
